package com.chimmhuang.util;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataTable;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Chimm Huang
 * @date 2020/01/22
 */
public class ContractUtil {

    private ContractUtil() {
    }

    /**
     * 调整bufferedimage大小
     * @param source BufferedImage 原始image
     * @param targetW int  目标宽
     * @param targetH int  目标高
     * @param flag boolean 是否同比例调整
     * @return BufferedImage  返回新image
     */
    public static BufferedImage resizeBufferedImage(BufferedImage source, int targetW, int targetH, boolean flag) {
        int type = source.getType();
        BufferedImage target = null;
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        if (flag && sx > sy) {
            sx = sy;
            targetW = (int) (sx * source.getWidth());
        } else if(flag && sx <= sy){
            sy = sx;
            targetH = (int) (sy * source.getHeight());
        }
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else {
            target = new BufferedImage(targetW, targetH, type);
        }
        Graphics2D g = target.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }


    public static Map<String, Object> getStringObjectMap(Object obj) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Class<?> aClass = obj.getClass();
        Field[] fields = aClass.getDeclaredFields();
        Map<String, Object> data = new HashMap<>(fields.length);
        for (Field field : fields) {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), aClass);
            Method method = pd.getReadMethod();
            String key = field.getName();
            Object value = method.invoke(obj);
            if (value != null) {
                data.put(key, value);
            }
        }
        return data;
    }


    public static void fillWordDataByMap(String templatePath, String targetPath, Map<String, Object> data, int fileType) {
        try (InputStream is = new FileInputStream(templatePath);
             OutputStream out = new FileOutputStream(targetPath)) {
            Document doc = new Document(is);
            DocumentBuilder builder = new DocumentBuilder(doc);
            Map<String, String> toData = new HashMap<>();
            for (Map.Entry<String, Object> en : data.entrySet()) {
                String key = en.getKey();
                Object value = en.getValue();
                if (key == null || value == null) {
                    continue;
                }
                if (value instanceof List) {
                    //写入表数据
                    DataTable dataTable = fillListData((List) value, key);
                    doc.getMailMerge().executeWithRegions(dataTable);
                }

                if (value instanceof BufferedImage) {
                    builder.moveToMergeField(key);
                    builder.insertImage((BufferedImage) value);
                }
                String valueStr = String.valueOf(en.getValue());
                toData.put(key, valueStr);
            }

            String[] fieldNames = new String[toData.size()];
            String[] values = new String[toData.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : toData.entrySet()) {
                fieldNames[i] = entry.getKey();
                values[i] = entry.getValue();
                i++;
            }
            //合并数据
            doc.getMailMerge().execute(fieldNames, values);
            doc.save(out, SaveOptions.createSaveOptions(fileType));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 封装 list 数据到 word 模板中（word表格）
     *
     * @param list      数据
     * @param tableName 表格列表变量名称
     * @return word表格数据DataTable
     */
    private static DataTable fillListData(List<Object> list, String tableName) throws Exception {
        //创建DataTable,并绑定字段
        DataTable dataTable = new DataTable(tableName);
        if (list == null || list.size() == 0) {
            return dataTable;
        }
        Class<?> objClass = list.get(0).getClass();
        Field[] fields = objClass.getDeclaredFields();
        // 绑定表头字段
        for (int i = 0; i < fields.length; i++) {
            dataTable.getColumns().add(fields[i].getName());
        }
        for (Object obj : list) {
            //创建DataRow，封装该行数据
            DataRow dataRow = dataTable.newRow();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), objClass);
                Method method = pd.getReadMethod();
                dataRow.set(i, method.invoke(obj));
            }
            dataTable.getRows().add(dataRow);
        }
        return dataTable;
    }

    //    private static License license = null;

    /**
     * 加载 license
     * 由于 aspose是收费的，若没有 license，则会出现水印。
     */
//    static {
//        try {
//            InputStream is = ContractUtil.class.getResourceAsStream("/license.xml");
//            license = new License();
//            license.setLicense(is);
//        } catch (Exception e) {
//            throw new RuntimeException("自动加载aspose证书文件失败!");
//        }
//    }
}
